package hang.study.uistudy;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by Administrator on 2015/10/27.
 */
public class TestDownloadActivity extends Activity {

    private TextView show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.test_download_layout);

        show = (TextView)findViewById(R.id.show);
    }

    public void download(View source) throws MalformedURLException{

        //Util.ShowMsg(this,"你单击了按钮");

        DownTask task = new DownTask(this);
        URL url = new URL("http://www.baidu.com");
        task.execute(url);
    }

    class DownTask extends AsyncTask<URL,Integer,String>{

        ProgressDialog pdialog;
        int hasRead = 0;
        Context mContext;

        public DownTask(Context ctx){
            mContext = ctx;
        }

        @Override
        protected String doInBackground(URL... params){
            StringBuilder sb = new StringBuilder();
            try{
                URLConnection conn = params[0].openConnection();
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(),"utf-8"));
                String line = null;
                while((line = br.readLine()) != null){
                    sb.append(line + "\n");
                    hasRead++;
                    publishProgress(hasRead);
                }

                return sb.toString();
            }catch (Exception e){
                Log.d(Util.LogTag,e.getMessage());
            }

            return null;
        }

        @Override
        protected void onPreExecute() {
            pdialog = new ProgressDialog(mContext);
            pdialog.setTitle("任务正在执行中");
            pdialog.setMessage("任务正在执行中，敬请等待……");
            pdialog.setCancelable(false);
            pdialog.setMax(202);
            pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pdialog.setIndeterminate(false);
            pdialog.show();
        }

        @Override
        protected void onPostExecute(String s) {
            show.setText(s);
            pdialog.dismiss();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            show.setText("已经读取了【"+values[0]+"】行！");
            pdialog.setProgress(values[0]);
        }
    }
}
